<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>

      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 消息提示 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <el-alert
          title="添加商品信息"
          type="info"
          center
          show-icon
          :closable="false"
        >
        </el-alert>
        <span></span>
      </div>

      <!-- 上边流程栏 -->
      <el-steps
        :active="activeNumber"
        finish-status="success"
        :align-center="true"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 左边栏Tabs的各个部分 -->

      <el-form
        :model="addFormGoods"
        :rules="addFormGoodsRules"
        label-width="100px"
        class="demo-ruleForm"
        ref="addGoodsForm"
      >
        <el-tabs
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
          v-model="activeTabs"
        >
          <!-- 添加基本信息 -->
          <el-tab-pane label="基本信息">
            <el-form-item label="活动名称" prop="goods_name" name="0">
              <el-input v-model="addFormGoods.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格" prop="goods_price" name="1">
              <el-input v-model="addFormGoods.goods_price"></el-input>
            </el-form-item>

            <el-form-item label="商品重量" prop="goods_weight" name="2">
              <el-input v-model="addFormGoods.goods_weight"></el-input>
            </el-form-item>

            <el-form-item label="商品数量" prop="goods_number" name="3">
              <el-input v-model="addFormGoods.goods_number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类" prop="goods_cat" name="4">
              <el-cascader
                v-model="addFormGoods.goods_cat"
                :options="cateList"
                :props="casaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品添加参数 -->
          <el-tab-pane label="商品参数">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  v-for="(item2, index) in item.attr_vals"
                  :key="index"
                  :label="item2"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品添加属性 -->
          <el-tab-pane label="商品属性"
            >商品属性
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input
                v-model="item.attr_vals"
                placeholder=""
                size="normal"
                clearable
              ></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品添加图片 -->

          <el-tab-pane label="商品图片">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-success="handleSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
              :headers="headersObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>

          <!-- 商品添加内容 -->
          <el-tab-pane label="商品内容">
            <quill-editor v-model="addFormGoods.goods_introduce"></quill-editor>
            <el-button
              type="primary"
              size="default"
              class="addGoodsBtn"
              @click="addGoods"
              >添加商品</el-button
            >
          </el-tab-pane>

          <!-- 完成 -->
          <el-tab-pane label="完成">完成</el-tab-pane>

        </el-tabs>
      </el-form>
      <!-- 基本信息表单 -->
    </el-card>
    <el-button style="margin-top: 12px" @click="prev">上一步</el-button>
    <el-button style="margin-top: 12px" @click="next">下一步</el-button>
    <!-- card body -->

    <!-- 添加参数 显示省略图的Dialog -->
    <el-dialog title="提示" :visible.sync="PreviewDialogVisible" width="50%">
      <img class="addimg" :src="PreviewPath" alt="" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="PreviewDialogVisible = false"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";

export default {
  data() {
    return {
      activeNumber: 0, //导航过程上边要的是Number型
      activeTabs: "0", //tabs左边要的是 name=""的string型
      addFormGoods: {
        goods_name: "",
        // addFormGoods差了数据goods_cat，导致没法length，整了一早上
        goods_cat: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: "",
        picsInfo: [],
        attrs: [],
      },
      PreviewDialogVisible: false,
      PreviewPath: "",
      cateList: [],
      casaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      manyTableData: [], //categories参数为many的值 （动态参数）
      onlyTableData: [], //only（静态属性）
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      fileList: [],
      headersObj: { Authorization: window.sessionStorage.getItem("token") },
      addFormGoodsRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
      },
      cateId: 0,
    };
  },

  methods: {
    // 添加商品
    async addGoods() {
      const { data: res } = await this.$http.post(`goods`, {
        params: addGoodsInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("post添加货物错误");
      } else this.$message.success("post添加货物成功");
    },
    next() {
      if (this.activeNumber++ > 4) this.activeNumber = 0;

      console.log(`activeNumber:${this.activeNumber}`);

      // 保持activeTabs和Number一致

      if (this.addFormGoods.goods_cat.length !== 3 && this.activeTabs == "0") {
        this.$message.error("没有选择三级分类");
        this.activeNumber = 0;
        return false;
      }
      this.activeTabs = this.activeNumber.toString();
    },
    prev() {
      if (this.activeNumber-- < 1) this.activeNumber = 4;
      // 保持activeTabs和Number一致

      if (this.addFormGoods.goods_cat.length !== 3 && this.activeTabs == "0") {
        this.$message.error("没有选择三级分类");
        this.activeNumber = 0;
        return false;
      }
      this.activeTabs = this.activeNumber.toString();
    },

    // 非三级cas清空
    handleChange() {
      console.log(this.addFormGoods.goods_cat);
      if (this.addFormGoods.goods_cat.length !== 3) {
        this.addFormGoods.goods_cat = []; //非三级清空goods_cat
      }
    },

    //
    beforeTabLeave(activeName, oldActiveName) {
      // console.log(this.addFormGoods.goods_cat);
      console.log(`变换前是${oldActiveName}+变换后是${activeName}`);
      console.log(`activeNumber:${this.activeNumber}`);
      if (this.addFormGoods.goods_cat.length !== 3 && oldActiveName == "0") {
        this.$message.error("没有选择三级分类");
        return false;
      } else {
        this.activeNumber = parseInt(activeName);
      }
    },

    // 获取商品分类以等级参数获取(也可以不用type)
    async getParentCatList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 3 },
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类列表失败");
      }
      this.cateList = res.data;
      console.log(this.cateList);

      return this.$message.success("get获取商品分类列表成功");
    },

    //

    // 先判定切换，如果是3级分类，则调用接口获取数据
    async tabClicked() {
      console.log(`activetabs:${this.activeTabs}`);
      // 通过基本信息商品分类的ID 以这个ID为数值 对 商品动态参数进行查询，从而添加参数

      // 判断是否选择了3级商品
      if (this.addFormGoods.goods_cat.length === 3 && this.activeNumber == 1) {
        const { data: res } = await this.$http.get(
          `categories/${this.addFormGoods.goods_cat[2]}/attributes`,
          { params: { sel: "many" } }
        );

        // 发送get请求请求动态参数
        if (res.meta.status !== 200) {
          return this.$message.error("get请求基本信息参数错误");
        } else {
          this.manyTableData = res.data;
          // 将attr_vals字符串转换为以' '为间隔的数组
          for (let i = 0; i < this.manyTableData.length; i++) {
            this.manyTableData[i].attr_vals =
              this.manyTableData[i].attr_vals.split(" ");
            console.log(this.manyTableData[i].attr_vals);
          }

          // console.log(this.manyTableData);
          // console.log(res);
          return this.$message.success("get请求基本信息参数成功");
        }
      }
      // 发送get请求请求静态属性
      else if (this.activeTabs === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.addFormGoods.goods_cat[2]}/attributes`,
          { params: { sel: "only" } }
        );

        if (res.meta.status !== 200) {
          return this.$message.error("get请求静态属性参数错误");
        }
        this.onlyTableData = res.data;

        console.log(res);
      }
    },
    // 成功
    handleSuccess(response) {
      console.log(response);
      const pic_Info = { pic: response.data.tmp_path };
      console.log(`${pic_Info.pic}`);
      this.addFormGoods.picsInfo.push(pic_Info.pic);
      console.log(this.addFormGoods);
    },

    // 图片预览 :on-preview
    handlePreview(file) {
      console.log(file);
      this.PreviewPath = file.response.data.url;
      this.PreviewDialogVisible = true;
    },
    // 图片移除 :on-remove
    handleRemove(file) {
      //
      console.log(file);
      const fileindex = this.addFormGoods.picsInfo.indexOf(
        file.response.data.tmp_path
      );

      // 视频用的方法
      /*    const fileindex=this.addFormGoods.picsInfo.findIndex( x=>{
            x.pic===file.response.data.tmp_path
          }) */

      console.log(`fileindex:${fileindex}`);
      this.addFormGoods.picsInfo.splice(fileindex, 1);
      console.log(this.addFormGoods);
      // const pic_Info={pic:response.data.tmp_path}

      //
    },

    // 添加商品确认button
    async addGoods() {
      this.$refs.addGoodsForm.validate((valid) => {
        if (!valid) {
          return this.$message.error("验证失败，检查表单数据");
        }
      });
      // 因为goods_cat是数组，在添加的时候需要转换为"1,2,3"这样的字符串
      const form = _.cloneDeep(this.addFormGoods);
      form.goods_cat = form.goods_cat.join(",");
      console.log(form.goods_cat);
      // 视频方法
      this.manyTableData.forEach((item) => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(" "),
        };
        this.addFormGoods.attrs.push(newInfo);
      });

      this.onlyTableData.forEach((item) => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_vallue: item.attr_vals,
        };
        this.addFormGoods.attrs.push(newInfo);
      });

      form.attrs = this.addFormGoods.attrs;
      console.log(form);
      const { data: res } = await this.$http.post("goods", form);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("post请求添加商品失败");
      }
      return this.$message.success("post添加商品成功");
    },
  },

  created() {
    this.getParentCatList();
  },
};
</script>

<style lang="less">
.addimg {
  width: 100%;
}
</style>